<template>
  <div class="mainPage" v-loading="loading">
    <router-view v-if="$route.name !== 'Main'"></router-view>
    <div  v-else class="admin-console">
    <Header />

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 顶部按钮组 -->
      <div class="top-buttons">
        <div class="left-buttons">
          <el-button type="primary" class="action-btn" @click="handleNormalAdmin">
            普通管理员列表
          </el-button>
          <el-button type="primary" class="action-btn" @click="handleSuperAdmin">
            超级管理员账户管理
          </el-button>
        </div>
        <div class="right-buttons">
          <el-button type="danger" class="action-btn" @click="handleBack">
            前往管理员控制台 →
          </el-button>
          <el-button type="warning" class="action-btn logout-btn" @click="handleLogout">
            退出登录
          </el-button>
        </div>
      </div>

      <!-- 专项处理部门管理 -->
      <div class="department-section" v-loading="departmentsLoading">
        <h2 class="section-title">专项处理部门管理</h2>

        <div class="departments-container">
          <!-- 提案专项处理部门 -->
          <div class="department-group">
            <h2 class="department-title">提案专项处理部门</h2>
            <div class="department-content">
              <el-button type="primary" class="add-btn" @click="handleAddDepartment('proposal')">
                添加部门+
              </el-button>
              <div class="department-list">
                <div v-for="(dept, index) in proposalDepartments" :key="index" class="department-item"
                  :class="{ 'active': dept.active }">
                  <el-icon class="delete-icon" @click="handleDeleteDepartment('proposal', index)">
                    <Delete />
                  </el-icon>
                  <span class="department-name">{{ dept.name }}</span>
                  <el-icon class="check-icon" @click="toggleDepartment('proposal', index)">
                    <Check />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>

          <!-- 社情民意专项处理部门 -->
          <div class="department-group">
            <h2 class="department-title">社情民意专项处理部门</h2>
            <div class="department-content">
              <el-button type="primary" class="add-btn" @click="handleAddDepartment('social')">
                添加部门+
              </el-button>
              <div class="department-list">
                <div v-for="(dept, index) in socialDepartments" :key="index" class="department-item"
                  :class="{ 'active': dept.active }">

                  <el-icon class="delete-icon" @click="handleDeleteDepartment('social', index)">
                    <Delete />
                  </el-icon>
                  <span>{{ dept.name }}</span>
                  <el-icon class="check-icon" @click="toggleDepartment('social', index)">
                    <Check />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
 
</template>

<script setup>
import Header from '@/components/header.vue'
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Delete, Check } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {  addProDepartment, addPubDepartment, deleteProDepartment, deletePubDepartment } from '@/api/super'
import { useAdminStore } from '@/stores/admin' // 引入 Pinia store
import { useDepartmentStore } from '@/stores/department'
import { useTokenStore } from '@/stores/token' // 引入 token store

const router = useRouter()
const adminStore = useAdminStore() // 创建 store 实例
const departmentStore = useDepartmentStore()
const tokenStore = useTokenStore() // 创建 token store 实例
const currentTime = ref('')
const loading = ref(false)
const departmentsLoading = ref(false)

// 部门数据
const proposalDepartments = computed(() => departmentStore.proposalDepartments)
const socialDepartments = computed(() => departmentStore.socialDepartments)

// 获取部门列表数据
const fetchDepartments = async () => {
  departmentsLoading.value = true
  try {
    await departmentStore.fetchDepartments()
  } catch (error) {
    ElMessage.error('获取部门列表失败')
  } finally {
    departmentsLoading.value = false
  }
}

// 处理添加部门
const handleAddDepartment = async (type) => {
  try {
    const { value: deptName } = await ElMessageBox.prompt('请输入部门名称', '添加部门', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: (value) => {
        if (!value) {
          return '部门名称不能为空'
        }
        return true
      }
    })

    if (deptName) {
      const newDept = {
        name: deptName,
        active: false
      }

      if (type === 'proposal') {
        await addProDepartment(newDept)
      } else {
        await addPubDepartment(newDept)
      }

      ElMessage.success('添加部门成功')
      fetchDepartments() // 重新获取列表
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加部门失败')
    }
  }
}

// 处理删除部门
const handleDeleteDepartment = async (type, index) => {
  try {
    await ElMessageBox.confirm('确定要删除该部门吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const departments = type === 'proposal' ? proposalDepartments.value : socialDepartments.value
    const deptId = departments[index].id

    if (type === 'proposal') {
      await deleteProDepartment(deptId)
    } else {
      await deletePubDepartment(deptId)
    }
    fetchDepartments() // 重新获取列表
    ElMessage.success('删除部门成功')
    
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除部门失败')
    }
  }
}

// 切换部门状态
const toggleDepartment = (type, index) => {
  const departments = type === 'proposal' ? proposalDepartments.value : socialDepartments.value
  departments[index].active = !departments[index].active
}

// 导航处理
const handleNormalAdmin = () => {
  router.push('/main/admin-list')
}

const handleSuperAdmin = () => {
  const currentAdminAid = adminStore.adminInfo.aid
  router.push(`/main/admin-info/${currentAdminAid}`)
}

const handleBack = () => {
  window.open('http://47.113.226.163:5174/login', '_blank')
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 清除token和管理员信息
    tokenStore.removeToken()
    adminStore.clearAdminInfo()
    
    // 跳转到登录页面
    router.push('/login')
    ElMessage.success('已成功退出登录')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退出登录失败')
    }
  }
}

// 更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '.')
}

onMounted(() => {
  updateTime()
  setInterval(updateTime, 1000)
  fetchDepartments() 
})
</script>

<style scoped>
@import '@/assets/css/main.css';
</style> 